//
//  PKRequestManager.m
//  PianKe
//
//  Created by lanou on 15/9/26.
//  Copyright (c) 2015年 李伟伟. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager
+(void)requestWithType:(RequestType)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error
{
    PKRequestManager *manager = [[PKRequestManager alloc]init];
    
    [manager requestWithType:type urlString:urlString parDic:parDic finish:finish error:error];
}

-(void)requestWithType:(RequestType)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error
{
    //拿到参数后进行请求
    NSURL *url = [NSURL URLWithString:urlString];
    //创建可变的URLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //如果请求方式是POST需要设置参数和请求方式
    if (type == POST) {
        //设置请求方式
        [request setHTTPMethod:@"POST"];
        if (parDic.count > 0) {
            NSData *data = [self parDicToDataWithDic:parDic];
            //设置请求参数的body体
            [request setHTTPBody:data];
        }
        
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            finish(data);
        }else{
            error(connectionError);
        }
    }];
}


//把参数字典 转为POST请求需要的参数体
-(NSData *)parDicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    //遍历字典得到每一个键 得到所有的key = value类型的字符串
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:str];
    }
    //数组里所有的key=value的字符串通过符号&连接
    NSString *parString = [array componentsJoinedByString:@"&"];
    //字符串转换成data类型
    return [parString dataUsingEncoding:NSUTF8StringEncoding];
}


@end
